﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using IO = System.IO;
using System.Collections.ObjectModel;
using Forms = System.Windows.Forms;
using System.Threading;
using System.Windows.Threading;
using MOJsdk;

namespace MOJ
{
    /// <summary>
    /// Interaction logic for Control_HandleFiles.xaml
    /// </summary>
    public partial class Control_HandleFiles : UserControl
    {
        private ObservableCollection<File2Add> _files;
        private ObservableCollection<File2Add> _toAdd;

        public Control_HandleFiles()
        {
            InitializeComponent();
            INI();
        }

        private void INI()
        {
            _files = new ObservableCollection<File2Add>();
            _toAdd = new ObservableCollection<File2Add>();

            INIEvents();
            INIStyle();
            INIVars();

            _listView_Files.ItemsSource = _files;
            _listView_files2add.ItemsSource = _toAdd;
        }
        private void INIEvents()
        {
            _btnSetFolder.Click += SetFolder;
            _btnSearch.Click += Search;
            _btnAdd.Click += AddFiles;
            _listView_Files.SelectionChanged += delegate { _btnRemove.IsEnabled = _listView_Files.SelectedIndex != -1; };
            _btnRemove.Click += RemoveFile;
            _btnAll.Click += SelectAll;
            _btnNone.Click += SelectNone;

            this.Loaded += LoadVars;
            this.Unloaded += SaveVars;
        }
        private void INIStyle()
        {
            _lblFilter.Content = MOJLocalization.Localize("Filter") + ": ";
            _lblFolder.Content = MOJLocalization.Localize("Folder") + ": ";
            _btnAdd.Content = MOJLocalization.Localize("Add");
            _btnRemove.Content = MOJLocalization.Localize("Remove");

            _progBar_isWaiting.IsEnabled = false;

            //_txtBox_folderPath.Text = @"D:\Downloads\Torrent\TehConnection";

            _grid.ApplyStyle("0101085");

            _lblFilter.ApplyStyle("0101086");
            _lblFolder.ApplyStyle("0101087");
            _listView_Files.ApplyStyle("0101088");
            _listView_files2add.ApplyStyle("0101089");
            _txtBox_Filter.ApplyStyle("0101090");
            _txtBox_folderPath.ApplyStyle("0101091");
            _btnAdd.ApplyStyle("0101092");
            _btnRemove.ApplyStyle("0101093");
            _btnSetFolder.ApplyStyle("0101094");
            _btnSearch.ApplyStyle("0101095");
            _btnAll.ApplyStyle("0101096");
            _btnNone.ApplyStyle("0101097");
            _progBar_isWaiting.ApplyStyle("0101124");

            _btnRemove.IsEnabled = false;
        }
        private void INIVars()
        {
            MojSystem _sys = GlobalVars.TheHost.SystemVars;

            if (!_sys.VarExist("MoJBrowseFilesDir"))
                _sys.SetVar("MoJBrowseFilesDir", @"C:\");
        }

        public List<File2Add> FilesToAdd
        { get { return new List<File2Add>(_files); } }
        public void RemoveAt(int index)
        {
            if (index < _files.Count)
                _files.RemoveAt(index);
        }

        private void SetFolder(object sender, RoutedEventArgs e)
        {
            Forms.FolderBrowserDialog diag = new Forms.FolderBrowserDialog();
            diag.Description = MOJLocalization.Localize("Select Folder");

            if (diag.ShowDialog() == Forms.DialogResult.OK)
            {
                _txtBox_folderPath.Text = diag.SelectedPath;
            }
        }

        private void Search(object sender, RoutedEventArgs e)
        {
            if (_txtBox_Filter.Text.IsNullorEmpty() || _txtBox_folderPath.Text.IsNullorEmpty())
                return;

            string folder = _txtBox_folderPath.Text;
            string filter = _txtBox_Filter.Text;

            thread2String th = new thread2String(AsyncSearch);
            th.BeginInvoke(folder, filter, null, null);
        }
        private void AsyncSearch(string folder, string filter)
        {
            this.Dispatcher.BeginInvoke(DispatcherPriority.Send, (ThreadStart)delegate
            {
                IsWaiting(true);
            });

            
            List<File2Add> files = new List<File2Add>();
            foreach (var v in TOOLS.GetFiles(folder, filter))
            {
                files.Add(new File2Add(v));
            }

            this.Dispatcher.BeginInvoke(DispatcherPriority.Send, (ThreadStart)delegate
            {
                _toAdd.Clear();
                foreach (var v in files)
                    _toAdd.Add(v);
                IsWaiting(false);
            });
        }

        private void AddFiles(object sender, RoutedEventArgs e)
        {
            foreach(var v in _toAdd)
            {
                if(v.IsSelected && !_files.Contains(v, new File2AddComparer()))
                {
                    _files.Add(v);
                }
            }
        }
        private void IsWaiting(bool value)
        {
            _txtBox_Filter.IsEnabled = !value;
            _txtBox_folderPath.IsEnabled = !value;
            _btnSearch.IsEnabled = !value;
            _btnSetFolder.IsEnabled = !value;
            _btnAll.IsEnabled = !value;
            _btnNone.IsEnabled = !value;
            _listView_Files.IsEnabled = !value;
            _listView_files2add.IsEnabled = !value;

            _progBar_isWaiting.IsEnabled = value;
            _progBar_isWaiting.IsIndeterminate = value;
        }

        private void RemoveFile(object sender, RoutedEventArgs e)
        {
            int x = _listView_Files.SelectedIndex;
            if (x == -1)
                return;

            _files.RemoveAt(x);
            try
            {
                _listView_Files.SelectedIndex = 0;
            }
            catch { }
        }
        private void SelectAll(object sender, RoutedEventArgs e)
        {
            foreach (var v in _toAdd)
                v.IsSelected = true;

            _listView_files2add.ItemsSource = null;
            _listView_files2add.ItemsSource = _toAdd;
        }
        private void SelectNone(object sender, RoutedEventArgs e)
        {
            foreach (var v in _toAdd)
                v.IsSelected = false;
            _listView_files2add.ItemsSource = null;
            _listView_files2add.ItemsSource = _toAdd;
        }

        private void LoadVars(object sender, RoutedEventArgs e)
        {
            MojSystem _sys = GlobalVars.TheHost.SystemVars;

            _txtBox_folderPath.Text = _sys.GetVar("MoJBrowseFilesDir");
            _txtBox_Filter.Text = _sys.GetVar("VideoType") + ";" + _sys.GetVar("SubtitleType");
        }
        private void SaveVars(object sender, RoutedEventArgs e)
        {
            GlobalVars.TheHost.SystemVars.SetVar("MoJBrowseFilesDir", _txtBox_folderPath.Text);
        }

        private delegate void thread2String(string folder, string filter);
    }

    public class File2Add
    {
        public File2Add(string PATH, bool SELECTED = false)
        {
            FilePath = PATH;
            IsSelected = SELECTED;
        }

        public string FilePath
        { get; set; }
        public string FileName
        {
            get { return IO.Path.GetFileName(FilePath); }
        }
        public bool IsSelected
        { get; set; }
    }
    public class File2AddComparer : IEqualityComparer<File2Add>
    {

        public bool Equals(File2Add b1, File2Add b2)
        {
            if (b1.FilePath.ToLower() == b2.FilePath.ToLower())
                return true;

            return false;
        }


        public int GetHashCode(File2Add bx)
        {
            return bx.GetHashCode();
        }
    }
}
